import { createRouter, createWebHistory } from "vue-router";
import Layout from "../layout/Layout.vue";
import { useUserStore } from "@/store/user";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "Login",
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/",
      component: Layout,
      redirect: "/dashboard",
      children: [
        {
          path: "dashboard",
          name: "Dashboard",
          component: () => import("../views/Dashboard.vue"),
        },
        {
          path: "users",
          name: "Users",
          component: () => import("../views/Users.vue"),
        },
        {
          path: "ai-model",
          name: "AiModel",
          redirect: "/ai-model/setting",
          children: [
            {
              path: "setting",
              name: "Setting",
              component: () => import("../views/ai-model/Setting.vue"),
            },
            {
              path: "collection",
              name: "Collection",
              component: () => import("../views/ai-model/Collection.vue"),
            },
          ],
        },
        {
          path: "profile",
          name: "Profile",
          component: () => import("../views/Profile.vue"),
        },
        {
          path: "employees",
          name: "Employees",
          component: () => import("../views/Employees.vue"),
          meta: { requiresAdmin: true },
        },
        {
          path: "feedback",
          name: "Feedback",
          component: () => import("../views/Feedback.vue"),
        },
        {
          path: "article",
          name: "Article",
          component: () => import("../views/Article.vue"),
        },
        {
          path: "question",
          name: "Question",
          component: () => import("../views/Question.vue")
        },
        {
          path: '/:pathMatch(.*)*',  // 匹配所有未知路径
          redirect: '/',            // 重定向到首页
        }
      ],
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {

  const userInfo = useUserStore().userInfo;

  // 如果去登录页面
  if (to.path == "/login") {
    // 用户信息存在，则跳转到首页
    if (userInfo) {
      next("/");
      // 用户信息不存在，则正常访问登录页
    } else {
      next();
    }
  } else {
    // 如果去其他页面
    // 用户信息不存在，则跳转到登录页
    if (!userInfo) {
      next("/login");
      // 用户信息存在，则正常访问其他页面
    } else {
      next();
    }
  }
});

export default router;